<?php

namespace App\Http\Controllers\File;

use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Service\Aliyunoss;
use App\Service\CodeService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

/**
 * @group 文件上传
 * Class UploadController
 * @package App\Http\Controllers\File
 */
class UploadController extends Controller
{
    /**
     * uploadFile 上传文件
     * @time:2020/2/6-11:44
     * @param Request $request
     * @author:dongdong
     * @bodyParam files required formdata 格式 可添加数组或单个文件.
     * @response {
     * "data": {
     * },
     * "status_code": 200,
     * "message" : "success"
     * }
     */
    public function uploadFile(Request $request)
    {
        $files = $request->file('files');
        $user_id = auth()->user()->id ?? 'common';
        $arrFile = [];
        if (is_array($files)) {
            $arrFile = $files;
        } else {
            $arrFile[] = $files;
        }
        $result = [];
        foreach ($arrFile as $file) {
            $tmp = $file;
            $path = '/uploads/user'; //public下的article
            if ($tmp && $tmp->isValid()) { //判断文件上传是否有效
                $FileType = $tmp->getClientOriginalExtension(); //获取文件后缀
                $allow = ["jpg","png","rar","txt","zip","doc","ppt","xls","pdf","docx","xlsx",'mp4','ogv','ogg','avi'];
                if (!in_array($FileType, $allow)) {
                    throw new ApiException("不支持此格式" . $FileType . '请上传' . implode(',', $allow));
                }

                $size = $tmp->getSize();
                if ($size > config('upload.max_size') )  {
                    throw new ApiException("上传文件过大请小于50M" );
                }

                $FilePath = $tmp->getRealPath(); //获取文件临时存放位置

                $FileName = $path . '/' . $user_id . '/' . date('Y-m-d') . uniqid() . '.' . $FileType; //定义文件名
                Storage::disk('public')->put($FileName, file_get_contents($FilePath)); //存储文件
                $host = $request->getSchemeAndHttpHost();
                $fileurl = $host . $FileName;
                $result[] = $fileurl;

            } else {
                throw new ApiException($tmp->getClientOriginalName() . '不是文件，请重新上传');
            }
        }
        return returnData($result);
    }


    /**
     * ossUpload oss toke
     */
    public function getOssToken(Request $request)
    {
        $data = (new Aliyunoss())->makeAliyunOssSignData();
        return returnData($data);
    }

    public function getAliossUrlAccess(Request $request) {
        $data = $request->validate([
            'url' => 'required|exists:house_imgs,file',
        ],[
            'exists'=> '数据文件不存在'
        ]);

        $url = urloss($data['url']);
        return returnData(['url'=>$url]);
    }

}
